package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SystemUserService systemUserService;


    @Override
    public CaptchaVo sendCode() {
        //生成验证码
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);//位数
        captcha.setCharType(SpecCaptcha.TYPE_DEFAULT);//数字，字符串，特殊符号
        String imageBase64 = captcha.toBase64();//获取图片base64
        String code = captcha.text();//获取验证码值
        //2.正确验证码的值+uuid存储到redis中
        String uuidKey = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");//获取uuid
        redisTemplate.opsForValue().set(uuidKey, code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
       //3.拼接CaptchaVo （验证码图片和uuid）
        CaptchaVo captchaVo = new CaptchaVo(imageBase64, uuidKey);//返回给前端
        return captchaVo;
    }


    @Override
    public String login(LoginVo loginVo) {
        //1.验证码校验是否过期
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        //验证码不存在
        if (ObjectUtils.isEmpty(redisCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);//验证码已过期
        }

        //校验验证码是否正确
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);//验证码错误
        }

        //验证账号是否存在
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);//用户不存在
        }
        //验证密码
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!systemUser.getPassword().equals( password)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);//密码错误
        }
        //验证状态
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);//账号禁用
        }
        //生成token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }

    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        //解析token获取claims 用户id
        Claims claims = JwtUtil.parseToken(accessToken);
        //获取用户信息  claims获取userId
        Integer userId = (Integer) claims.get("userId");
        //获取用户信息  userId查询用数据
        SystemUser systemUser = systemUserService .getById(userId);
        // SystemUserInfoVo 构建
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getUsername());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());

        return systemUserInfoVo;
    }
}
